package org.example.AI;

import java.util.Stack;

/**
 * @author: 默苍璃
 * @date: 2024-07-18 11:06
 */
// 表达式解析器，负责解析用户输入的表达式字符串，并构建相应的表达式对象
public class ExpressionParser {
    public Expression parse(String input) {
        String[] tokens = input.split("\\s+");

        Stack<Expression> stack = new Stack<>();

        for (String token : tokens) {
            if (isOperator(token)) {
                if (stack.size() < 2) {
                    throw new IllegalArgumentException("表达式格式错误：操作数数量不足");
                }
                Expression right = stack.pop();
                Expression left = stack.pop();
                stack.push(createExpression(token, left, right));
            } else {
                stack.push(new NumberExpression(Integer.parseInt(token)));
            }
        }

        if (stack.size() != 1) {
            throw new IllegalArgumentException("表达式格式错误：操作符数量错误");
        }

        return stack.pop();
    }

    private boolean isOperator(String token) {
        return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/");
    }

    private Expression createExpression(String token, Expression left, Expression right) {
        switch (token) {
            case "+":
                return new AddExpression(left, right);
            // 减法、乘法、除法类似，请自行添加
            default:
                throw new IllegalArgumentException("不支持的操作符：" + token);
        }
    }
}